package com.zengjianjun.hadoop.demo.controller;

import com.zengjianjun.hadoop.demo.client.HadoopClient;
import com.zengjianjun.hadoop.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author zengjianjun
 */
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @Resource
    private HadoopClient hadoopClient;

    /**
     * 上传文件
     */
    @PostMapping("upload")
    public R<?> upload(@RequestParam MultipartFile file) {
        hadoopClient.upload(file);
        return R.ok();
    }

    /**
     * 下载文件
     */
    @GetMapping("download")
    public void download(@RequestParam String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        response.setCharacterEncoding("utf8");
        response.setContentType("application/force-download");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream os;
        try {
            os = response.getOutputStream();
            hadoopClient.download(fileName, os);
        } catch (Exception e) {
            log.error("file download error:", e);
        }
    }
}
